package com.spring.housing.feign;

import com.spring.housing.constant.Constants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
@Slf4j
@Configuration
public class RequestConfig implements RequestInterceptor {

/*
*在调用feign是将需要的token传入client端
 */
    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        template.header("accessToken", Constants.ACCESSTOKEN);
        log.info("feign AccessTOKEN{}",Constants.ACCESSTOKEN);
        if (headerNames == null) {
            return;
        }
        //处理上游请求头信息，传递时继续携带
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            if (name.equals("content-length")) continue;
            String values = request.getHeader(name);
            template.header(name, values);
        }
    }
}
